package edu.kpi.pzks2.ui;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import javax.swing.JFileChooser;


public class GraphMenuBarListeners {
    public static <T extends Serializable> void save(final T saveObject, final Component parent) {
        try { 
            final JFileChooser fileDialog = new JFileChooser();
            fileDialog.showDialog(parent, "Save");

            if (fileDialog.getSelectedFile() == null) return;

            final FileOutputStream outStream = new FileOutputStream(fileDialog.getSelectedFile()); 
            ObjectOutputStream oos = new ObjectOutputStream(outStream); 
            oos.writeObject(saveObject);
            oos.flush(); 
            oos.close(); 
        } 
        catch(Exception ex) { 
            System.out.println("Exception during serialization: " + ex); 
        } 
    }

    public static <T extends Serializable> ActionListener getOpenListener(
            final LoadListener<T> loadListener,
            final Component parent) {
        return new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Object deserialization 
                try { 
                    final JFileChooser fileDialog = new JFileChooser();
                    fileDialog.showDialog(parent, "Open");

                    if (fileDialog.getSelectedFile() == null) return;

                    FileInputStream fis = new FileInputStream(fileDialog.getSelectedFile()); 
                    ObjectInputStream ois = new ObjectInputStream(fis); 
                    @SuppressWarnings("unchecked")
                    final T loadedObject = (T) ois.readObject(); 
                    ois.close();

                    loadListener.objectLoaded(loadedObject);
                } 
                catch(Exception exc) { 
                    System.out.println("Exception during deserialization: " + 
                            exc); 
                } 
            }
        };
    }

    public interface LoadListener<T extends Serializable> {
        void objectLoaded(T loadedObject);
    }

    public static ActionListener getNewListener(final GraphEditor editor) {
        return new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                editor.newGraph();
            }
        };
    }
}
